using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model;

namespace WPF_MVVM_Test.Services.Plan
{
    /// <summary>
    /// 产品服务类
    /// </summary>
    public class ProductService : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private const string BASE_URL = "http://8.140.242.140:8888/api/Productentity/GetProductList";

        public ProductService()
        {
            _httpClient = new HttpClient();
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };
        }

        /// <summary>
        /// 获取产品列表
        /// </summary>
        public async Task<(List<ProductModel> products, int totalCount, int totalPage)> GetProductsAsync(
            string? materialNumber = "",
            string? materialName = "",
            string? materialType = "",
            string? materialProperty = "",
            int pageIndex = 1,
            int pageSize = 10)
        {
            try
            {
                var queryParams = BuildQueryParameters(materialNumber, materialName, materialType, materialProperty, pageIndex, pageSize);
                var requestUrl = $"{BASE_URL}?{queryParams}";

                System.Diagnostics.Debug.WriteLine($"🌐 请求URL: {requestUrl}");

                var response = await _httpClient.GetAsync(requestUrl);

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"📦 API响应: {jsonContent}");

                    var apiResponse = JsonSerializer.Deserialize<ProductApiResponse>(jsonContent, _jsonOptions);

                    if (apiResponse?.IsSuc == true && apiResponse.Data?.Data != null)
                    {
                        AssignIndexToProducts(apiResponse.Data.Data, (pageIndex - 1) * pageSize);
                        
                        System.Diagnostics.Debug.WriteLine($"✅ 成功获取 {apiResponse.Data.Data.Count} 条记录，总计 {apiResponse.Data.TotalCount} 条");
                        
                        return (
                            apiResponse.Data.Data,
                            apiResponse.Data.TotalCount,
                            apiResponse.Data.TotalPage
                        );
                    }
                    else
                    {
                        throw new Exception($"API返回错误: {apiResponse?.Msg ?? "未知错误"}");
                    }
                }
                else
                {
                    throw new Exception($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"❌ API请求异常: {ex.Message}");
                return GetTestData(materialNumber, materialName, pageIndex, pageSize);
            }
        }

        /// <summary>
        /// 构建查询参数
        /// </summary>
        private string BuildQueryParameters(string? materialNumber, string? materialName, string? materialType, string? materialProperty, int pageIndex, int pageSize)
        {
            var queryParams = new List<string>();

            if (!string.IsNullOrWhiteSpace(materialNumber))
                queryParams.Add($"MaterialNumber={Uri.EscapeDataString(materialNumber)}");

            if (!string.IsNullOrWhiteSpace(materialName))
                queryParams.Add($"MaterialName={Uri.EscapeDataString(materialName)}");

            if (!string.IsNullOrWhiteSpace(materialType))
                queryParams.Add($"MaterialType={Uri.EscapeDataString(materialType)}");

            if (!string.IsNullOrWhiteSpace(materialProperty))
                queryParams.Add($"MaterialProperty={Uri.EscapeDataString(materialProperty)}");

            queryParams.Add($"PageIndex={pageIndex}");
            queryParams.Add($"PageSize={pageSize}");

            return string.Join("&", queryParams);
        }

        /// <summary>
        /// 为产品列表分配序号
        /// </summary>
        private void AssignIndexToProducts(List<ProductModel> products, int skipCount)
        {
            for (int i = 0; i < products.Count; i++)
            {
                products[i].Index = skipCount + i + 1;
            }
        }

        /// <summary>
        /// 获取测试数据（API失败时使用）
        /// </summary>
        private (List<ProductModel>, int, int) GetTestData(string? materialNumber, string? specificationModel, int pageIndex, int pageSize)
        {
            var testProducts = new List<ProductModel>
            {
                new ProductModel
                {
                    Index = 1,
                    Id = Guid.NewGuid().ToString(),
                    MaterialNumber = "CP025",
                    MaterialName = "智能手机",
                    SpecificationModel = "华为mate",
                    Unit = "台",
                    MaterialType = "成品",
                    MaterialProperty = "自制",
                    Status = "启用"
                },
                new ProductModel
                {
                    Index = 2,
                    Id = Guid.NewGuid().ToString(),
                    MaterialNumber = "CP026",
                    MaterialName = "智能手机",
                    SpecificationModel = "小米14",
                    Unit = "台",
                    MaterialType = "成品",
                    MaterialProperty = "自制",
                    Status = "启用"
                }
            };

            // 简单的筛选逻辑
            var filteredProducts = testProducts.Where(p =>
                (string.IsNullOrEmpty(materialNumber) || p.MaterialNumber.Contains(materialNumber, StringComparison.OrdinalIgnoreCase)) &&
                (string.IsNullOrEmpty(specificationModel) || p.SpecificationModel.Contains(specificationModel, StringComparison.OrdinalIgnoreCase))
            ).ToList();

            return (filteredProducts, filteredProducts.Count, 1);
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}



